"""
自定义用户登录的认证类，实现多字段登录

"""

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from rest_framework.exceptions import ParseError

from apps.system.models import User


class MyBackend(ModelBackend):

    # 自定义的登录认证类
    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            user = User.objects.get(Q(username=username) | Q(email=username) | Q(mobile=username))
        except:
            raise ParseError({'code': 400, 'msg': '未找到该用户！'})



        else:
            # 验证密码
            if user.check_password(password):
                return user
            else:
                raise ParseError({'code': 400, 'msg': '密码不正确！'})
